package com.xjscrm.console.common.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

public class MyExcelUtil {

    public static void exportExcel(HttpServletResponse response, List<String> titles, List<Object> matchedObjects, List<String> fields) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + "数据导出" + ".xls");
        OutputStream outputStream = response.getOutputStream();
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        // Create a header row
        String[] titlesArray = titles.toArray(new String[0]);
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < titlesArray.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(titlesArray[i]);
        }

        // Create body
        for (int i = 0; i < matchedObjects.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Map<String, Object> fieldsMap = (Map<String, Object>) matchedObjects.get(i);
            int cellIndex = 0;
            for (String field : fields) {
                Cell cell = row.createCell(cellIndex++);
                Object value = fieldsMap.get(field);
                cell.setCellValue(value != null ? value.toString() : "");
            }
        }
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
